<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="60%">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="customerId">
            <el-select
              filterable
              clearable
              v-model="formData.customerId"
              placeholder="请选择客户"
              class="w-1/1"
              @change="handleCustomerChange"
            >
              <el-option
                v-for="item in customerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="订单名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入订单名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="订单编号" prop="no">
            <el-input disabled v-model="formData.no" placeholder="保存时自动生成" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="下单人" prop="ownerUserId">
            <el-select
              v-model="formData.ownerUserId"
              :disabled="true"
              class="w-1/1"
            >
              <el-option
                v-for="item in userOptions"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="税率" prop="taxRate">
            <el-input v-model="formData.taxRate" placeholder="请输入税率" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="店铺名称" prop="storeName">
            <el-input v-model="formData.storeName" placeholder="请输入店铺名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="店铺面积" prop="storeArea">
            <el-input v-model="formData.storeArea" placeholder="请输入店铺面积" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="业务员" prop="signUserId">
            <el-select v-model="formData.signUserId" class="w-1/1">
              <el-option
                filterable
                clearable
                v-for="item in userOptions"
                :key="item.id"
                :label="item.nickname"
                :value="item.id!"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客户订单编号" prop="customerOrderNo">
            <el-input v-model="formData.customerOrderNo" placeholder="请输入客户订单编号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="手工订单编号" prop="manualOrderNo">
            <el-input v-model="formData.manualOrderNo" placeholder="请输入手工订单编号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="销售范围" prop="salesScope">
            <el-input v-model="formData.salesScope" placeholder="请输入销售范围" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="销售代理商" prop="salesAgent">
            <el-input v-model="formData.salesAgent" placeholder="请输入销售代理商" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="订单类型" prop="orderType">
            <el-select
              filterable
              clearable
              v-model="formData.orderType"
              placeholder="请选择订单类型"
              class="w-1/1"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.TRADE_ORDER_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="订单状态" prop="orderStatus">
            <el-select
              filterable
              clearable
              v-model="formData.orderStatus"
              placeholder="请选择订单状态"
              class="w-1/1"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.TRADE_ORDER_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="约定发货时间" prop="shipTime">
            <el-date-picker
              v-model="formData.shipTime"
              type="date"
              value-format="x"
              placeholder="选择发货时间"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="约定到货时间" prop="deliveryTime">
            <el-date-picker
              v-model="formData.deliveryTime"
              type="date"
              value-format="x"
              placeholder="选择到货时间"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="交货方式" prop="deliveryType">
            <el-select
              filterable
              clearable
              v-model="formData.deliveryType"
              placeholder="请选择交货方式"
              class="w-1/1"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.TRADE_DELIVERY_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="收货联系人" prop="contactName">
            <el-input v-model="formData.contactName" placeholder="请输入收货联系人" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系人电话" prop="signContactPhone">
            <el-input v-model="formData.signContactPhone" placeholder="请输入联系人电话" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发货单号" prop="slipNo">
            <el-input disabled v-model="formData.slipNo" placeholder="发货时自动生成" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="收货地区" prop="areaId">
            <el-cascader
              clearable
              filterable
              v-model="formData.areaId"
              :options="areaList"
              :props="defaultProps"
              class="w-1/1"
              placeholder="请选择收货地区"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="收货详细地址" prop="detailAddress">
            <el-input v-model="formData.detailAddress" placeholder="请输入收货详细地址" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 子表的表单 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="订单文件" prop="file">
            <el-upload
              ref="uploadRef"
              v-model:file-list="fileList"
              :disabled="formLoading"
              :on-exceed="handleExceed"
              :on-remove="handleRemove"
              :auto-upload="false"
              :on-change="handleImport"
              :limit="1"
              :show-file-list="true"
              accept=".xlsx, .xls"
              action="none"
            >
              <Icon icon="ep:upload" />
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <template #tip>
                <div class="el-upload__tip text-center">
                  <span>仅允许导入 xls、xlsx 格式文件。</span>
                  <el-link
                    :underline="false"
                    style="font-size: 12px; vertical-align: baseline"
                    type="primary"
                    @click="importTemplate"
                  > 下载模板
                  </el-link>
                </div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item label="请选择Sheet页" prop="sheetNo">
            <el-radio-group v-model="formData.sheetNo">
              <el-radio
                v-for="sheet in sheetOptions"
                :onchange="handleChecked"
                :key="sheet.value"
                :value="sheet.value"
              >
                {{ sheet.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" placeholder="请输入备注说明" type="textarea" :rows="5"/>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-show="false">
          <el-form-item label="整单折扣（%）" prop="discountPercent">
            <el-input-number
              v-model="formData.discountPercent"
              placeholder="请输入整单折扣"
              controls-position="right"
              :min="0"
              :model-value="0"
              :precision="2"
              class="!w-1/1"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">保存</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import XLSX, {writeFile} from 'xlsx'
import moment from 'moment'
import { DICT_TYPE, getIntDictOptions ,getStrDictOptions} from '@/utils/dict'
import { defaultProps, handleTree } from '@/utils/tree'
import * as CustomerApi from '@/api/crm/customer'
import * as ContractApi from '@/api/crm/contract'
import * as UserApi from '@/api/system/user'
import { useUserStore } from '@/store/modules/user'
import * as AreaApi from "@/api/system/area";
import download from "@/utils/download";
import {UploadUserFile} from "element-plus";

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('导入订单产品') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  no: undefined,
  name: undefined,
  customerId: undefined,
  businessId: undefined,
  orderDate: undefined,
  startTime: undefined,
  endTime: undefined,
  signUserId: undefined,
  signContactId: undefined,
  ownerUserId: undefined,
  discountPercent: 0,
  totalProductPrice: undefined,
  remark: undefined,
  products: [],
  storeId: undefined,
  storeName: undefined,
  storeArea: undefined,
  contactName: undefined,
  slipNo: undefined,
  orderType: undefined,
  orderStatus: undefined,
  deliveryType: undefined,
  shipTime: undefined,
  deliveryTime: undefined,
  signContactPhone: undefined,
  areaId: undefined,
  detailAddress: undefined,
  salesScope: undefined,
  salesAgent: undefined,
  customerOrderNo: undefined,
  manualOrderNo: undefined,
  taxRate: 13,
  sheetNo: 0,
})
const formRules = reactive({
  name: [{ required: true, message: '订单名称不能为空', trigger: 'blur' }],
  customerId: [{ required: true, message: '客户不能为空', trigger: 'blur' }],
  // orderDate: [{ required: true, message: '下单日期不能为空', trigger: 'blur' }],
  ownerUserId: [{ required: true, message: '负责人不能为空', trigger: 'blur' }],
  storeName: [{ required: true, message: '店铺名称不能为空', trigger: 'blur' }],
  // auditStatus: [{ required: true, message: '审批状态不能为空', trigger: 'blur' }],
  orderStatus: [{ required: true, message: '订单状态不能为空', trigger: 'blur' }],
  orderType: [{ required: true, message: '订单类型不能为空', trigger: 'change' }],
  contactName: [{ required: true, message: '联系人不能为空', trigger: 'change' }],
  signContactPhone: [{ required: true, message: '联系电话不能为空', trigger: 'change' }],
  // areaId: [{ required: true, message: '收货地区不能为空', trigger: 'change' }],
  detailAddress: [{ required: true, message: '详细地址不能为空', trigger: 'change' }],
  sheetNo: [{ required: true, message: 'sheet不能为空', trigger: 'change' }],
})
const formRef = ref() // 表单 Ref
const userOptions = ref<UserApi.UserVO[]>([]) // 用户列表
const customerList = ref([]) // 客户列表的数据
const areaList = ref([]) // 地区列表
const fileList = ref<UploadUserFile[]>([]) // 文件列表
const sheetOptions = ref([]) // 分类列表
/** 子表的表单 */
const subTabsName = ref('product')

/** 打开弹窗 */
const open = async (type: string, id?: number, customerId?: number) => {
  dialogVisible.value = true
  // dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 获得客户列表
  customerList.value = await CustomerApi.getCustomerSimpleList()
  // 获得用户列表
  userOptions.value = await UserApi.getSimpleUserList()
  // 获得地区列表
  areaList.value = await AreaApi.getAreaTree()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ContractApi.getContract(id)
    } finally {
      formLoading.value = false
    }
  }
  // 默认新建时选中自己
  if (formType.value === 'create') {
    formData.value.ownerUserId = useUserStore().getUser.id
    formData.value.orderStatus = '10'
    // formData.value.deliveryType = '1'
    // formData.value.orderType = '01'
    formData.value.sheetNo = 0
  }
  if (customerId) {
    formData.value.customerId = customerId
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {debugger
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    // const data = unref(formData.value) as unknown as ContractApi.ContractVO
    const uploadFormData = getUploadFormData()
    if (formType.value === 'create') {
      if (fileList.value.length == 0) {
        message.error('请上传备货单文件')
        return
      }
      // 将文件对象 file 添加到 formData 对象中，uploadFile 需要与后端接口中接收文件的参数名一致，如果不一致，则后端需要指定参数名，如 @RequestPart("uploadFile") MultipartFile file
      uploadFormData.append("file", fileList.value[0].raw as Blob);
      const res =  await ContractApi.importContractAndProduct(uploadFormData)
      // message.success(t('common.createSuccess'))
      submitFormSuccess(res)
    } else {
      const data = unref(formData.value) as unknown as ContractApi.ContractVO
      await ContractApi.updateContract(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
const submitFormSuccess = (response: any) => {
  if (response.code !== 0) {
    message.error(response.msg)
    formLoading.value = false
    return
  }
  const formType = response.formType
  const data = response.data
  let insertCount = data.createProductNames.length
  let updateCount = data.updateProductNames.length
  let errorCount = Object.keys(data.failureProductNames).length
  let text = ""
  if(formType === "update" && insertCount===0 && updateCount===0 && errorCount===0){
    // 更新返回结果，且未上传文件
    text = "更新成功"
  }else{
    // 拼接提示语
    text = '成功数量：' + insertCount + ';'
    // for (let productName of data.createProductNames) {
    //   text += '< ' + productName + ' >'
    // }
    // text += '更新成功数量：' + updateCount + ';'
    // for (const productName of data.updateProductNames) {
    //   text += '< ' + productName + ' >'
    // }
    text += '失败数量：' + errorCount + ';'
    for (const msg in data.failureProductNames) {
      text += '< ' + msg + ': ' + data.failureProductNames[msg] + ' >'
    }
  }
  message.alert(text)
  if(insertCount>0 || updateCount>0 || errorCount<=0){
    formLoading.value = false
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  }else{
    formLoading.value = false
    return
  }
}

/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')
  formLoading.value = false
}
const getUploadFormData = () =>{
  const uploadFormData = new FormData();
  // 将普通对象 qualityFileObj 的属性添加到 uploadFormData 对象中
  if(formData.value.no){
    uploadFormData.append("no", formData.value.no as string);
  }
  if(formData.value.name){
    uploadFormData.append("name", formData.value.name as string);
  }
  if(formData.value.customerId){
    uploadFormData.append("customerId", formData.value.customerId  as number);
  }
  if(formData.value.projectName){
    uploadFormData.append("projectName", formData.value.projectName as string);
  }
  if(formData.value.signUserId){
    uploadFormData.append("signUserId", formData.value.signUserId as number);
  }
  if(formData.value.signContactId){
    uploadFormData.append("signContactId", formData.value.signContactId as number);
  }
  if(formData.value.ownerUserId){
    uploadFormData.append("ownerUserId", formData.value.ownerUserId as number);
  }
  if(formData.value.orderDate){
    uploadFormData.append("orderDate", formattedDate(formData.value.orderDate) as Date);
  }
  if(formData.value.startTime){
    uploadFormData.append("startTime", formattedDate(formData.value.startTime) as Date);
  }
  if(formData.value.endTime){
    uploadFormData.append("endTime", formattedDate(formData.value.endTime) as Date);
  }
  if(formData.value.shipTime){
    uploadFormData.append("shipTime", formattedDate(formData.value.shipTime) as Date);
  }
  if(formData.value.deliveryTime){
    uploadFormData.append("deliveryTime", formattedDate(formData.value.deliveryTime) as Date);
  }
  if(formData.value.discountPercent){
    uploadFormData.append("discountPercent", formData.value.discountPercent as number);
  }
  if(formData.value.totalProductPrice){
    uploadFormData.append("totalProductPrice", formData.value.totalProductPrice as number);
  }
  if(formData.value.remark){
    uploadFormData.append("remark", formData.value.remark as string);
  }
  if(formData.value.storeName){
    uploadFormData.append("storeName", formData.value.storeName as string);
  }
  if(formData.value.salesAgent){
    uploadFormData.append("salesAgent", formData.value.salesAgent as string);
  }
  if(formData.value.customerOrderNo){
    uploadFormData.append("customerOrderNo", formData.value.customerOrderNo as string);
  }
  if(formData.value.manualOrderNo){
    uploadFormData.append("manualOrderNo", formData.value.manualOrderNo as string);
  }
  if(formData.value.storeArea){
    uploadFormData.append("storeArea", formData.value.storeArea as string);
  }
  if(formData.value.signContactPhone){
    uploadFormData.append("signContactPhone", formData.value.signContactPhone as string);
  }
  if(formData.value.detailAddress){
    uploadFormData.append("detailAddress", formData.value.detailAddress as string);
  }
  if(formData.value.areaId){
    uploadFormData.append("areaId", formData.value.areaId as number);
  }
  if(formData.value.slipNo){
    uploadFormData.append("slipNo", formData.value.slipNo as number);
  }
  if(formData.value.orderStatus){
    uploadFormData.append("orderStatus", formData.value.orderStatus as number);
  }
  if(formData.value.orderType){
    uploadFormData.append("orderType", formData.value.orderType as number);
  }
  if(formData.value.deliveryType){
    uploadFormData.append("deliveryType", formData.value.deliveryType as number);
  }
  if(formData.value.contactName){
    uploadFormData.append("contactName", formData.value.contactName as number);
  }

  if(formData.value.note){
    uploadFormData.append("note", formData.value.note as string);
  }
  uploadFormData.append("sheetNo", formData.value.sheetNo as number);

  return uploadFormData;
}
// 时间戳转换为yyyy-MM-dd HH:mm:ss
const formattedDate = (time: any) => {
  const date = new Date(time);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${second}`;
};

const FileDate = (date: number, type: String) => {debugger
  if (date) {
    let year, month, day, HH, mm, ss;
    const time = new Date((date - 2) * 24 * 3600000 + 1 - 8 * 3600000);
    time.setFullYear(time.getFullYear() - 70);
    console.log('time', time);
    let timeDate;
    year = time.getFullYear(); // 年
    month = time.getMonth() + 1; // 月
    day = time.getDate(); // 日
    HH = time.getHours(); // 时
    mm = time.getMinutes(); // 分
    ss = time.getSeconds(); // 秒

    month = month < 10 ? '0' + month : month;
    day = day < 10 ? '0' + day : day;
    HH = HH < 10 ? '0' + HH : HH; // 时
    mm = mm < 10 ? '0' + mm : mm; // 分
    ss = ss < 10 ? '0' + ss : ss; // 秒

    switch (type) {
      case 'yyyy':
        timeDate = String(year);
        break;
      case 'yyyy-MM':
        timeDate = year + '-' + month;
        break;
      case 'yyyy-MM-dd':
        timeDate = year + '-' + month + '-' + day;
        break;
      case 'yyyy/MM/dd':
        timeDate = year + '/' + month + '/' + day;
        break;
      case 'yyyy-MM-dd HH:mm:ss':
        timeDate = year + '-' + month + '-' + day + ' ' + HH + ':' + mm + ':' + ss;
        break;
      case 'yyyy-MM-dd_HH:mm:ss':
        timeDate = year + '-' + month + '-' + day + '_' + HH + ':' + mm + ':' + ss;
        break;
      case 'yyyy-MM-dd HH:mm':
        timeDate = year + '-' + month + '-' + day + ' ' + HH + ':' + mm;
        break;
      case 'HH:mm:ss':
        timeDate = HH + ':' + mm + ':' + ss;
        break;
      case 'MM':
        timeDate = String(month);
        break;
      case 'dd':
        timeDate = String(day);
        break;
      default:
        timeDate = year + '-' + month + '-' + day;
        break;
    }
    return timeDate;
  } else {
    return '';
  }
};

/** 重置表单 */
const resetForm = async() => {
  formData.value = {
    id: undefined,
    no: undefined,
    name: undefined,
    customerId: undefined,
    businessId: undefined,
    orderDate: undefined,
    startTime: undefined,
    endTime: undefined,
    signUserId: undefined,
    signContactId: undefined,
    ownerUserId: undefined,
    discountPercent: 0,
    totalProductPrice: undefined,
    remark: undefined,
    customerOrderNo: undefined,
    manualOrderNo: undefined,
    taxRate: 13,
    sheetNo: 0,
    products: []
  }

  // 重置上传状态和文件
  fileList.value = []
  sheetOptions.value = []
  await nextTick()
  formRef.value?.clearFiles()
  // formRef.value?.resetFields()
}

/** 处理选择sheet表格 */
const handleChecked = () => {
  // alert(formData.value.sheetNo)
  // 解析工作表
  const firstSheetName = workbookObj.value.SheetNames[formData.value.sheetNo];
  const worksheet = workbookObj.value.Sheets[firstSheetName];

  // 转换为二维数组 [[表头], [行数据]...]
  const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

  // 提取表头
  // tableHeaders.value = jsonData[0];
  formData.value.customerId =  getCustomer(jsonData[0][1])
  formData.value.orderType = getOrderType(jsonData[1][1])
  formData.value.manualOrderNo = jsonData[2][1]
  formData.value.customerOrderNo = jsonData[3][1]
  formData.value.contactName = jsonData[4][1]
  formData.value.detailAddress = jsonData[5][1]
  formData.value.signContactPhone = jsonData[6][1]
  formData.value.shipTime = (FileDate(jsonData[7][1] as number,'yyyy/MM/dd'))
  formData.value.storeName = jsonData[8][1]
  formData.value.salesAgent = jsonData[9][1]
  formData.value.storeArea = jsonData[10][1]
  formData.value.orderDate = jsonData[11][1]
  formData.value.remark = jsonData[14][1]

}

/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error('最多只能上传一个文件！')
}

/** 下载模板操作 */
const importTemplate = async () => {
  const res = await ContractApi.importContractTemplate()
  download.excel(res, '产品订单模板.xls')
}
//移除文件的操作方法
const handleRemove = (file) => {

}

const tableHeaders = ref([]);  // 存储表头信息
const workbookObj = ref();  // 存储表格数据
const tableData = ref([]);
const getSheetOptions =(sheetNameArr) => {
  sheetOptions.value =  sheetNameArr.map((sheet, index) => ({
    label: sheet,
    value: index
  }));
};

const handleImport = (file) => {
  // 文件类型校验
  if(!/\.xlsx|\.xls$/.test(file.name)) {
    message.error("仅支持 Excel 文件");
    return;
  }
  sheetOptions.value = undefined
  formData.value.name = file.name
  const reader = new FileReader();
  reader.onload = (e) => {
    try {
      // 读取文件内容
      const data = new Uint8Array(e.target.result);
      workbookObj.value = XLSX.read(data, { type: "array" });
      const workbook = XLSX.read(data, { type: "array" });
      getSheetOptions(workbook.SheetNames)
      // 解析第一个工作表
      const firstSheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[firstSheetName];

      // 转换为二维数组 [[表头], [行数据]...]
      const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

      // 提取表头
      tableHeaders.value = jsonData[0];
      // console.info(tableHeaders.value[1])
      formData.value.customerId =  getCustomer(jsonData[0][1])
      formData.value.orderType = getOrderType(jsonData[1][1])
      formData.value.manualOrderNo = jsonData[2][1]
      formData.value.customerOrderNo = jsonData[3][1]
      formData.value.contactName = jsonData[4][1]
      formData.value.detailAddress = jsonData[5][1]
      formData.value.signContactPhone = jsonData[6][1]
      formData.value.shipTime = (FileDate(jsonData[7][1] as number,'yyyy/MM/dd'))
      formData.value.storeName = jsonData[8][1]
      formData.value.salesAgent = jsonData[9][1]
      formData.value.storeArea = jsonData[10][1]
      formData.value.orderDate = jsonData[11][1]
      formData.value.remark = jsonData[14][1]


      // 构造对象数组
      tableData.value = jsonData.slice(1).map(row => {
        return tableHeaders.value.reduce((obj, header, index) => {
          obj[header] = row[index] || "";
          return obj;
        }, {});
      });

      message.success("读取成功");
    } catch (error) {
      message.error(`读取失败: ${error.message}`);
    }
  };
  // 以 ArrayBuffer 格式读取文件
  reader.readAsArrayBuffer(file.raw);
};

/** 获取客户联系人 */
const getCustomer =  (customerName) => {
  return customerList.value.filter((item) => item.name == customerName)[0].id
}

const getOrderType =  (orderTypeName) => {
  return getStrDictOptions(DICT_TYPE.TRADE_ORDER_TYPE).filter((item) => item.label == orderTypeName)[0].value
}

const exportExcel = () => {
  // 将对象数组转为工作表
  const worksheet = XLSX.utils.json_to_sheet(tableData.value);

  // 创建工作簿并添加工作表
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");

  // 触发文件下载
  XLSX.writeFile(workbook, "data.xlsx");
};

</script>
